import React, { Component } from 'react'
import {Input, Radio, Upload, Button, Message} from 'element-react'
import Select from '../base/Select'
import DatePicker from '../base/DatePicker'
import {withRouter} from 'react-router-dom'
import Breadcrumb from '../base/Breadcrumb'
import Quill from 'quill'
import 'quill/dist/quill.snow.css'
import { spawn } from 'child_process';

class goodsOperate extends Component {
  constructor (props) {
    super(props)
    this.state = {
      // 提交参数
      "categoryId": '',
      "endTime": "",
      "id": '',
      "imgs": null,
      "name": "",
      "postfAdvertise": "",
      "preAdvertise": "",
      "sellerId": '',
      "startTime": "",
      "status": 1,
      "description": '',
      // 编辑页展示已上传的图片
      fileList2: [],
      // 一级分类
      oneType: [],
      secondType: [],
      thirdType: []
    }
    this.editor = null
    this.imgs = []
  }
  componentDidMount () {
    this.selectOneTyprArr()
    // 编辑情况下更新数据
    if (this.props.match.params.id) {
      this.selectModifProduct()
    } else {
      this.addQuill()
    }
  }
  // 加入富文本框
  addQuill () {
    const textbox = this.refs.textarea
    const toolbarOptions = [
      ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
      ['blockquote', 'code-block'],
      [{ 'header': 1 }, { 'header': 2 }],               // custom button values
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
      [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
      [{ 'direction': 'rtl' }],
      [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
      [{ 'font': [] }],
      [{ 'align': [] }],
      ['image', 'video'],
      ['clean']                                         // remove formatting button
    ]
    const options = {
      debug: 'warn',
      modules: {
        toolbar: toolbarOptions
      },
      placeholder: '请输入文本...',
      readOnly: false,
      theme: 'snow'
    }
    let editor =this.editor= new Quill(textbox,options)
    let {description}=this.state
    if (description) editor.clipboard.dangerouslyPasteHTML(description)
    editor.on('text-change', this.handleChange.bind(this))
  }
  handleChange () {
    let {description}=this.state
    description = this.editor.root.innerHTML
    this.setState({description})
  }
  // 查找一级分类数据
  selectOneTyprArr () {
    this.$ajax.selectOneType().then(res => {
      if (res.code === 200) {
        let oneTypeArr = res.data.map((a) => {
          a.label = a.name
          a.value = a.id
          return a
        })
        this.setState({oneType: oneTypeArr})
      } else {
        Message.error(res.msg)
      }
    }).catch(() => {
      Message.error('网络错误')
    })
  }
  // 根据id查询产品详情
  selectModifProduct () {
    this.$ajax.selectModifProduct(this.props.match.params.id).then(res => {
      if (res.code === 200) {
        let fileList2 = []
        if (res.data.imgVos !== null) {
          fileList2 = res.data.imgVos.map(a => {
            a.name = a.id
            return a
          })
        }
        if (res.data.imgVos !== null) {
          this.imgs = res.data.imgVos
        }
        this.setState({
          categoryId: res.data.categroyIds,
          endTime: res.data.endTime,
          id: res.data.id,
          imgs: res.data.imgVos,
          name: res.data.name,
          postfAdvertise: "",
          preAdvertise: "",
          sellerId: res.data.sellerName,
          startTime: res.data.startTime,
          status: res.data.status,
          description: res.data.description,
          fileList2: fileList2
        }, () => {this.addQuill()})
        console.log(this.state)
      } else {
        Message.error(res.msg)
      }
    }).catch(() => {
      Message.error('网络错误')
    })
  }
  handleSuccess (response, file, fileList) {
    console.log(this.imgs)
    if (this.imgs.length > 5) {
      Message.error('上传图片不超过6张')
    }
    this.imgs.push(
      {
        url: response.data,
        operation: 1,
        id: ''
      }
    )
  }
  remove (file, fileList) {
    console.log(file)
    let t = this.imgs.findIndex((a) => {
      return a.url === file.response.data
    })
    console.log(t)
    this.imgs.splice(t, 1)
    console.log(this.imgs)
  }
  statusFun (val) {
    this.setState({status: val})
  }
  getTime (begin, end) {
    this.setState(
      {
        startTime: new Date(begin),
        endTime: new Date(end)
      }
    )
  }
  cancel () {
    this.props.history.goBack()
  }
  submit () {
    let {categoryId, endTime, id, name, postfAdvertise, preAdvertise, sellerId, startTime, status, description} = this.state
    let imgs = this.imgs
    console.log({categoryId, endTime, id, name, postfAdvertise, preAdvertise, sellerId, startTime, status, description})
    if (!name || !sellerId || !postfAdvertise || !preAdvertise || !startTime || !endTime || !description) {
      Message('请输入完整信息')
      return
    }
    if (imgs.length > 6) {
      Message.error('上传图片不超过6张')
      return
    }
    if (!categoryId) {
      Message.error('请选择第三级分类')
      return
    }
    let data = {categoryId, endTime, id, imgs, name, postfAdvertise, preAdvertise, sellerId, startTime, status, description}
    if (this.props.match.params.id) {
      this.$ajax.modifProduct(data).then(res => {
        if (res.code === 200) {
          Message({
            message: '提交成功',
            type: 'success'
          })
          this.props.history.goBack()
        } else {
          Message.error('提交失败')
        }
      }).catch(() => {
        Message.error('网络错误')
      })
    } else {
      this.$ajax.createProduct(data).then(res => {
        if (res.code === 200) {
          Message({
            message: '提交成功',
            type: 'success'
          })
          this.props.history.goBack()
        } else {
          Message.error('提交失败')
        }
      }).catch(() => {
        Message.error('网络错误')
      })
    }
  }
  showUpload () {
    if (this.state.fileList2.length > 0) {
      return (
        <Upload
              className="upload-demo"
              action="http://tft-dev/api3/upload/file"
              onSuccess={(response, file, fileList) => this.handleSuccess(response, file, fileList)}
              onError={(err, file, fileList) => {Message.error('提交失败')}}
              listType="picture"
              fileList={this.state.fileList2}
              onRemove={this.remove.bind(this)}>
          <Button size="small" type="primary">点击上传</Button>
        </Upload>
      )
    } else {
      return (
        <span>
          <Upload
            className="upload-demo"
            action="http://tft-dev/api3/upload/file"
            onSuccess={(response, file, fileList) => this.handleSuccess(response, file, fileList)}
            onError={(err, file, fileList) => {Message.error('提交失败')}}
            listType="picture"
            fileList={this.state.fileList2}
            onRemove={this.remove.bind(this)}
          >
            <Button size="small" type="primary">点击上传</Button>
          </Upload>
        </span>
      )
    }
  }
  oneType (value) {
    this.$ajax.selectOtherType(value).then(res => {
      if (res.code === 200) {
        let secondTypeArr = res.data.map((a) => {
          a.label = a.name
          a.value = a.id
          return a
        })
        this.setState({
          secondType: secondTypeArr,
          categoryOneId: value,
          categorySecondId: '',
          categoryId: '',
          thirdType: []
        })
      }
    })
  }
  secondType (value) {
    this.$ajax.selectOtherType(value).then(res => {
      if (res.code === 200) {
        let thirdTypeArr = res.data.map((a) => {
          a.label = a.name
          a.value = a.id
          return a
        })
        this.setState({
          thirdType: thirdTypeArr,
          categorySecondId: value,
          categoryId: ''
        })
      }
    })
  }
  thirdType (value) {
    this.setState({
      categoryId: value
    })
  }
  render () {
    return (
      <div className="goods-operate">
        {
          this.props.match.params.id ? <Breadcrumb data={['商品管理', '商品列表', '编辑']}/> : <Breadcrumb data={['商品管理', '商品列表', '新增']}/>
        }
        <div className="height30"></div>
        <div className="inputGroup">
          <label className="inputLabel">产品名称：</label>
          <Input placeholder="请输入产品名称" size="small" className="inputSmall" value={this.state.name} onChange={value => {this.setState({name: value})}}/>
        </div>
        <div className="inputGroup">
          <label className="inputLabel">产品卖家：</label>
          <Input size="small" className="inputSmall" value={this.state.sellerId} onChange={sellerId => {this.setState({sellerId})}}/>
        </div>
        <div className="inputGroup">
          <label className="inputLabel">产品卖点：</label>
          <div className="inline-marginR-20">
            <Input  placeholder="前置广告语" size="small" className="inputSmall" value={this.state.preAdvertise} onChange={value => {this.setState({preAdvertise: value})}}/>
          </div>
          <Input placeholder="后置广告语" size="small" className="inputSmall" value={this.state.postfAdvertise} onChange={value => {this.setState({postfAdvertise: value})}}/>
        </div>
        <div className="inputGroup">
          <label className="inputLabel">产品分类：</label>
          <div className="inline-marginR-20">
            <Select options={this.state.oneType} value={this.state.categoryOneId} select={this.oneType.bind(this)}/>
            <div className="width20"></div>
            <Select options={this.state.secondType} value={this.state.categorySecondId} select={this.secondType.bind(this)}/>
            <div className="width20"></div>
            <Select options={this.state.thirdType} value={this.state.categoryId} select={this.thirdType.bind(this)}/>
          </div>
        </div>
        <div className="inputGroup">
          <label className="inputLabel">产品缩略图：</label>
          <div className="inline-marginR-20">
          {this.showUpload.call(this)}
          </div>
        </div>
        <div className="inputGroup">
          <label className="inputLabel">产品描述：</label>
          <div className="quill">
            <div ref="textarea"></div>
          </div>
        </div>
        <div className="inputGroup">
          <label className="inputLabel">产品有效期：</label>
          {
            this.props.match.params.id ? <DatePicker getTime={this.getTime.bind(this)} startTime={this.state.startTime} endTime={this.state.endTime} setValue={true}/> : <DatePicker getTime={this.getTime.bind(this)}/>
          }

        </div>
        {/* 状态 */}
        <div className="inputGroup">
          <label className="inputLabel">状态：</label>
          <Radio.Group value={this.state.status} onChange={this.statusFun.bind(this)}>
            <Radio value="1">已上架</Radio>
            <Radio value="0">未上架</Radio>
          </Radio.Group>
        </div>
        <button type="button" className="btn btn-cancel" onClick={this.cancel.bind(this)}>取消</button>
        <button type="button" className="btn btn-save" onClick={this.submit.bind(this)}>保存</button>
      </div>
    )
  }
}
export default withRouter(goodsOperate)